#!/usr/bin/env python
# encoding=utf-8

import sys
from uuid import uuid4

from flask import request, session
from flask.ext.login import UserMixin
from xtls.timeparser import now
from xtls.util import sha512

import dao
from . import login_manager

reload(sys)
sys.setdefaultencoding('utf-8')


@login_manager.user_loader
def load_user(user_id):
    return User(**dao.select_db_single(db='lawyer_asst', coll='user', filter={'uuid': user_id}))


class UserLog(dict):
    def __init__(self, event, value):
        ip = request.headers.get('X-Forwarded-For', '').split(',')[0].strip()
        if not ip:
            ip = request.headers.get('X-Real-Ip', None)
            if not ip:
                ip = request.remote_addr
        super(UserLog, self).__init__(
            event=event,
            value=value,
            time=now(),
            user=session.get('user_id', None),
            uuid=session.get('uuid', None),
            ip=ip,
            ua=request.user_agent.string,
        )


class User(UserMixin):
    def __init__(self, **kwargs):
        self.username = kwargs['username']
        self.password = kwargs['password']
        self.phone = kwargs['phone']
        self.uuid = kwargs.get('uuid', uuid4().hex)
        self.createdtime = kwargs.get('createdtime', now())

    @classmethod
    def query(cls, **kwargs):
        if 'username' in kwargs:
            u = dao.select_db_single(coll='user', db='lawyer_asst', filter={'username': kwargs['username']})
        elif 'uuid' in kwargs:
            u = dao.select_db_single(coll='user', db='lawyer_asst', filter={'uuid': kwargs['uuid']})
        elif 'phone' in kwargs:
            u = dao.select_db_single(coll='user', db='lawyer_asst', filter={'phone': kwargs['phone']})
        else:
            raise ValueError('username or uuid not found')
        if u:
            return User(**u)
        return None

    def save(self):
        self.password = self.calc_password(self.password, self.createdtime)
        data = {
            'username': self.username,
            'password': self.password,
            'phone': self.phone,
            'uuid': self.uuid,
            'createdtime': self.createdtime
        }
        dao.insert_into_mongo('lawyer_asst', 'user', data)

    def verify_password(self, password):
        return self.password == self.calc_password(password, self.createdtime)

    def get_id(self):
        return self.uuid

    @classmethod
    def calc_password(cls, password, time):
        return sha512('{}uneverguess{}'.format(password, time.strftime('%Y-%m-%d %H:%M:%S')))

    def __str__(self):
        return u'<User> username: {}, uuid: {}, phone: {}'.format(self.username, self.uuid, self.phone)
